package com.jf.yytgd.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.jf.yytgd.service.TokenService;
import com.jf.yytgd.utils.JwtUtil;
import com.jf.yytgd.utils.Msg;
import com.jf.yytgd.utils.ObjectUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2025-02-24
 * Time:10:03
 */
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Msg msg = Msg.failed();
        try {
            JwtUtil.verifyToken(token);
            if (tokenService.verify(token)) {
                return HandlerInterceptor.super.preHandle(request, response, handler);
            } else {
                //todo 退出登录等操作
                return false;
            }
        } catch (SignatureVerificationException e) {
            log.info("Token signature verify failed", e);
            msg.addData("token", "invalid");
        } catch (TokenExpiredException e) {
            log.info("Token expired", e);
            msg.addData("token", "expired");
        } catch (AlgorithmMismatchException e) {
            log.warn("Token algorithm mismatch", e);
            msg.addData("token", "invalid");
        } catch (Exception e) {
            log.warn("Unconventional wrong with token", e);
        }
        String data = ObjectUtil.toJson(msg);
        if (StringUtils.hasText(data)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(data);
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String token = request.getHeader("token");
        // 已登录
        if (token != null) {
            String newToken = JwtUtil.updateExpiration(token);

        }
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
